const process = require("process");
const { caches, isObject, getUid } = require("./util");

const child = {
  /**
   * 发送信息 - child
   * @param {*} data
   * @param {*} callback
   */
  sendMsg(data = {}) {
    return new Promise((resolve) => {
      if (!isObject(data)) throw Error(`${data}不是object`);
      const uid = getUid();
      caches.set(uid, resolve);
      process.on("message", (data) => {
        const obj = JSON.parse(data);
        if(obj.status ==3){
          obj.status = 4
        } else {
          return
        }
        if (caches.has(obj.id) &&  obj.status == 4) {
          // 结束会话
          caches.get(obj.id)(obj.msg);
          caches.delete(obj.id);
        }
      })
     
      process.send(JSON.stringify({ id: uid, msg: data, status: 1 }));
    });
  },
  /**
   * 监听信息 - child
   * @param {*} callback
   */
  onMsg(callback) {
    process.on("message", (data) => {
      const obj = JSON.parse(data);
      if (obj.status == 1) obj.status = 2;
      function res(e) {
        if (!isObject(e)) throw Error(`${e}不是object`);
        if (obj.status == 2) {
          obj.status = 3;
        } else {
          // console.log('应答任务已结束',obj)
          return;
        }
        process.send(
          JSON.stringify({ id: obj.id, msg: e, status: obj.status })
        );
      }
      callback(obj.msg, res);
    });
  },
};

module.exports = child;
